package com.bestv.lucene;

import com.bestv.utils.database.DBConnectionManager;
import com.bestv.utils.database.JDBCHelper;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;

/**
 * 节目索引器
 * User: Henry
 * Date: 14-5-6
 */
public class ProgramIndexer {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private IndexWriter indexWriter;

    public ProgramIndexer(String indexDir) {
        try {
            Analyzer analyzer = new CJKAnalyzer();
            IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_4_10_4, analyzer);
            iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
            Directory dir = FSDirectory.open(new File(indexDir));
            indexWriter = new IndexWriter(dir, iwc);
        } catch (IOException e) {
            logger.error("Error on open directory: {}", indexDir, e);
        }
    }

    public void close() {
        try {
            indexWriter.close();
        } catch (IOException e) {
            logger.error("Error on close index writer.", e);
        }
    }

    public int index() {
        String sql = "SELECT Id, Name, TypeId, concat_ws(' ',Tags,Actors,Director,Keywords) AS Tags, Genre FROM series";
        Connection conn = DBConnectionManager.getSlaveConnection();
        ArrayList<Object[]> table = JDBCHelper.executeQuery(conn, sql);
        JDBCHelper.close(conn);
        return indexResultSet(table);
    }

    private int indexResultSet(ArrayList<Object[]> table) {
        try {
            for (Object[] row : table) {
                if (row[1] == null || row[4] == null) continue;
                Document doc = new Document();
                doc.add(new LongField("Id", (Long) row[0], Field.Store.YES));
                doc.add(new TextField("Name", (String)row[1], Field.Store.NO));
                doc.add(new IntField("TypeId", (Integer) row[2], Field.Store.NO));
                doc.add(new TextField("Tags", (String)row[3], Field.Store.NO));
                doc.add(new TextField("Genre", (String)row[4], Field.Store.NO));
                indexWriter.addDocument(doc);
            }
        } catch (IOException e) {
            logger.error("Error on index program.", e);
        }
        return indexWriter.numDocs();
    }
}
